<template>
  <div class="stock-in-management">
    <div class="page-title">能耗统计表</div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.devName" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item label="工厂名称">
          <el-input v-model="searchForm.factoryName" placeholder="请输入工厂名称" clearable />
        </el-form-item>
        <el-form-item label="车间名称">
          <el-input v-model="searchForm.workshop" placeholder="请输入车间名称" clearable />
        </el-form-item>
        <el-form-item label="产线名称">
          <el-input v-model="searchForm.productionLine" placeholder="请输入产线名称" clearable />
        </el-form-item>
        
        <!-- 时间查询区域 -->
        <el-form-item label="时间查询">
          <div class="time-query-group">
            <span class="time-type-label">类型:</span>
            <el-select v-model="timeType" style="width: 120px; margin-right: 10px;" >
              <el-option
                v-for="optionType in timeTypes"
                :key="optionType"
                :label="getTimeTypeLabel(optionType)"
                :value="optionType" 
              />
            </el-select>
            <el-date-picker
              v-model="selectedDate"
              :type="getDatePickerType(timeType)"
              range-separator="至"
              :start-placeholder="timeType.includes('range') ? '开始日期' : ''"
              :end-placeholder="timeType.includes('range') ? '结束日期' : '选择日期'"
              value-format="YYYY-MM-DD"
              :style="{ width: timeType.includes('range') ? '240px' : '140px' }" />
          </div>
        </el-form-item>
        
        <!-- 列显示控制 -->
        <el-form-item label="显示列">
          <el-checkbox-group v-model="selectedColumns">
            <el-checkbox 
              v-for="column in columnOptions" 
              :key="column.value" 
              :label="column.value"
              @change="handleColumnChange"
            >
              {{ column.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <el-table :data="stockInList" border  :summary-method="getSummaries" show-summary stripe v-loading="loading">
        <el-table-column 
          prop="dateTimeType" 
          label="时间" 
          width="160"
         
        >
          <!-- <template #default="scope">
            {{ formatDateTime(scope.row.dateTimeType) }}
          </template> -->
        </el-table-column>
        
        <el-table-column 
          prop="devName" 
          label="设备名称" 
          width="120"
          v-if="isColumnVisible('devName')"
        />
        
        <el-table-column 
          prop="factoryName" 
          label="工厂名称" 
          width="150"
          v-if="isColumnVisible('factoryName')"
        />
        
        <el-table-column 
          prop="workshop" 
          label="车间名称" 
          width="100"
          v-if="isColumnVisible('workshop')"
        />
        
        <el-table-column 
          prop="productionLine" 
          label="产线名称" 
          width="140"
          v-if="isColumnVisible('productionLine')"
        />
        
        <el-table-column 
          prop="substance" 
          label="物质" 
          width="120"
          v-if="isColumnVisible('substance')"
        />
 
        <el-table-column 
          prop="energyConsumption" 
          label="能耗" 
          width="100" 
          align="right"
          show-summary="true"
        >
          <!-- <template #default="scope">
            {{ formatNumber(scope.row.energyConsumption) }}
          </template> -->
        </el-table-column>
        
        <!-- <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column> -->
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 详情弹窗 -->
    <StockInDetail
      :visible="detailVisible"
      @update:visible="detailVisible = $event"
      :detail-data="currentDetail" />
  </div>
</template>

<script  setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { request } from '@/utils/request'
import { ElMessage } from 'element-plus'

// 导入组件
//import StockInDetail from './StockInDetail.vue'

// 响应式数据
const loading = ref(false)
const stockInList = ref([])
const detailVisible = ref(false)
const currentDetail = ref({})

// 搜索表单
const searchForm = reactive({
  devName: '',
  factoryName: '',
  workshop: '',
  productionLine: '',
  substance: '',
  timeType: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 时间类型相关
const timeType = ref('daterange')
const selectedDate = ref('')

// 时间类型选项
const timeTypes = [
  'year',
  'month',
  'date',
  'daterange',
  'monthrange',
  'yearrange'
]

// 列显示控制
const columnOptions = [
  { label: '设备名称', value: 'devName' },
  { label: '工厂名称', value: 'factoryName' },
  { label: '车间名称', value: 'workshop' },
  { label: '产线名称', value: 'productionLine' },
  { label: '物质', value: 'substance' },
]

// 表格合计行计算方法 - 只计算能耗数量列
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  
  columns.forEach((column, index) => {
    // 第一列显示"合计"文字
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    
    // 只在能耗数量列显示合计值
    if (column.property === 'energyConsumption') {
      const values = data.map(item => Number(item[column.property]))
      if (!values.every(value => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)
        // 格式化数字显示
        sums[index] = formatNumber(sums[index])
      } else {
        sums[index] = '0'
      }
    } else {
      // 其他列不显示合计值
      sums[index] = ''
    }
  })
  
  return sums
}

// 默认选中所有列
const selectedColumns = ref(columnOptions.map(col => col.value))

// 检查列是否可见
const isColumnVisible = (columnName) => {
  return selectedColumns.value.includes(columnName)
}

// 监听时间类型变化，清空选择的日期
watch(timeType, () => {
  selectedDate.value = ''
})

// 监听列选择变化，刷新数据
watch(selectedColumns, () => {
  // 当列选择变化时，重新加载数据
  handleColumnChange()
}, { deep: true })

// 列选择变化处理
const handleColumnChange = () => {
  // 重置到第一页，重新加载数据
  pagination.current = 1
  loadStockInData()
}
// 获取时间类型的中文标签
const getTimeTypeLabel = (type) => {
  const labelMap = {
    'year': '年',
    'month': '月',
    'date': '日',
    'daterange': '日期范围',
    'monthrange': '月份范围',
    'yearrange': '年份范围'
  }
  return labelMap[type] || type
}

// 根据时间类型获取对应的 date-picker 类型
const getDatePickerType = (type) => {
  const typeMap = {
    'year': 'year',
    'month': 'month',
    'date': 'date',
    'daterange': 'daterange',
    'monthrange': 'monthrange',
    'yearrange': 'yearrange'
  }
  return typeMap[type] || 'date'
}

// 格式化数字显示
const formatNumber = (value) => {
  if (value === null || value === undefined) return '0'
  return Number(value).toLocaleString()
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 加载能耗数据
const loadStockInData = async () => {
  loading.value = true
  try {
    // 处理时间查询条件
    let timeCondition = null
    let startDate, endDate
    if (selectedDate.value) {
      if (Array.isArray(selectedDate.value)) {
        // 范围选择
        startDate = selectedDate.value[0]
        endDate = selectedDate.value[1] 
        timeCondition = startDate + '至' + endDate
      } else {
        // 单个日期选择
        timeCondition = selectedDate.value
      }
    }
    
    // 构建查询参数
    const params = {
      filter: {
        PageIndex: pagination.current,
        PageSize: pagination.size,
        OrderBy: "DateTimeType",
        IsAscending: false
      },
      Energy: {
        DevName: searchForm.devName,
        FactoryName: searchForm.factoryName,
        Workshop: searchForm.workshop,
        ProductionLine: searchForm.productionLine,
        Substance: searchForm.substance,
        TimeType: timeType.value,
        TimeCondition: timeCondition,
        // 添加选中的列信息，供后端筛选返回字段
        SelectedColumns: selectedColumns.value
      }
    }
    
    // 调用后端API
    const response = await request.post('/Energy/EC/ReportPage', params)
    stockInList.value = response.data
    pagination.total = response.totalCount
  } catch (error) {
    console.error('加载记录失败:', error)
    ElMessage.error('加载记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadStockInData()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  timeType.value = 'daterange'
  selectedDate.value = ''
  // 重置列选择为全选
  selectedColumns.value = columnOptions.map(col => col.value)
  pagination.current = 1
  loadStockInData()
}

// 查看详情
const handleDetail = (row) => {
  currentDetail.value = { ...row }
  detailVisible.value = true
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadStockInData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.current = page
  loadStockInData()
}

// 页面加载时获取数据
onMounted(() => {
  loadStockInData()
})
</script>

<style scoped>
.stock-in-management {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.time-query-group {
  display: flex;
  align-items: center;
}

.time-type-label {
  margin-right: 8px;
  color: #606266;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

/* 列选择器的样式调整 */
:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

:deep(.el-checkbox) {
  margin-right: 15px;
}
</style>